package com.sjtu.rental.form;

import org.apache.commons.validator.GenericValidator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.sjtu.rental.entity.UserInfo;

@Component("loginForm")
public class LoginForm implements Validator {

	private UserInfo user = new UserInfo();

	public boolean supports(Class<?> arg0) {
		return LoginForm.class.equals(arg0);
	}

	public void validate(Object o, Errors e) {
		UserInfo ui = ((LoginForm) o).getUser();
		// 验证用户名
		if (GenericValidator.isBlankOrNull(ui.getUiUsername())
				&& GenericValidator.isBlankOrNull(ui.getUiEmail())) {
			e.rejectValue("user.uiUsername", "login.username.notNull");
		} else {
			if (!GenericValidator.isBlankOrNull(ui.getUiEmail())) {
				if (!GenericValidator.isEmail(ui.getUiEmail())) {
					e.rejectValue("user.uiUsername", "login.email.invalid");
				}
			} else {
				if (!GenericValidator.isBlankOrNull(ui.getUiUsername())
						&& !ui.getUiUsername().matches("^[a-zA-Z0-9]+$")) {
					e.rejectValue("user.uiUsername", "login.username.invalid");
				}
			}
		}
		// 验证密码
		if (GenericValidator.isBlankOrNull(ui.getUiPassword())) {
			e.rejectValue("user.uiPassword", "login.password.notNull");
		}
	}

	// getter and setter

	public UserInfo getUser() {
		return user;
	}

	public void setUser(UserInfo user) {
		this.user = user;
	}

}
